/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package engine.entities.inventory.item;

import engine.entities.inventory.item.MobEquipSet.EQUIP_SLOT;
import engine.game.Game;
import static engine.game.combat.ability.Ability.BACKGROUND_COLOR;
import engine.game.gfx.ColoredSprite;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.io.Serializable;
import java.util.ArrayList;
import javax.swing.ImageIcon;

/**
 *
 * @author Nathan T
 */
public abstract class Item implements Serializable {
    
    public final int SCALE = 2;
    private final String name;
    private final ColoredSprite sprite;
    private final ImageIcon icon;
    
    protected ArrayList<EQUIP_SLOT> equipSlots = new ArrayList<>();
    
    public Item(String name, ColoredSprite sprite) {
        this.name = name;
        this.sprite = sprite;
        this.icon = getImageIcon(sprite);
        
        this.initiateEquipSlots();
    }
    
    public abstract void initiateEquipSlots();
    
    private ImageIcon getImageIcon(ColoredSprite sprite) {
        BufferedImage bufferedIconImage = new BufferedImage(sprite.width(), sprite.height(), BufferedImage.TYPE_INT_RGB);
        int imagePixels[] = ((DataBufferInt) bufferedIconImage.getRaster().getDataBuffer()).getData();

        for (int i = 0; i < sprite.pixels().length; i++) {
            for (int j = 0; j < sprite.pixels()[0].length; j++) {
                if (sprite.pixels()[i][j] < 255) {
                    imagePixels[i + (j * sprite.width())] = Game.colors[sprite.pixels()[i][j]];
                }
                else {
                    imagePixels[i + (j * sprite.width())] = BACKGROUND_COLOR;
                }
            }
        }

        Image resizedImage = bufferedIconImage.getScaledInstance(sprite.width() * SCALE, sprite.height() * SCALE, Image.SCALE_SMOOTH);
        return new ImageIcon(resizedImage);
    }
    
    public ColoredSprite getSprite() {
        return sprite;
    }
    
    public ImageIcon getIcon() {
        return icon;
    }
    
    public String getName() {
        return name;
    }
    
    public boolean canStackWith(Item other) {
        if (!isStackable()) {
            return false;
        }
        return other.getClass().equals(this.getClass());
    }
    
    public boolean canEquipTo(EQUIP_SLOT slot) {
        if (slot == null) {
            return true;
        }
        for (EQUIP_SLOT testSlot : equipSlots) {
            if (slot.equals(testSlot)) {
                return true;
            }
        }
        return false;
    }
    
    public abstract boolean isStackable();
    
}
